package bio;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 客户端线程
 * @author zengwenming
 * 用于处理一个客户端的Socket链路
 */
public class ServerHandler implements Runnable{
    private Socket socket;
    public ServerHandler(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try(BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(),true);){

            String expression;
            String result;
            while(true){
                //通过BufferedReader读取一行
                //如果已经读到输入流尾部，返回null,退出循环
                //如果得到非空值，就尝试计算结果并返回
                if((expression = in.readLine())==null) break;
                System.out.println("服务器收到消息：" + expression);
                try{
                    String expressionArray[] = this.getExpressionArray(expression);
                    Double resultD = Double.parseDouble(expressionArray[0])+Double.parseDouble(expressionArray[1]);
                    result = expression + "=" + resultD;
                }catch(Throwable e){
                    result = "计算错误：" + e.getMessage();
                }
                out.println(result);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private String[] getExpressionArray(String expression){
        char operators[] = {'+','-','*','/'};
        for(char o : operators){
            System.out.println("getExpressionArray o="+o);
            String expressionArray[] = expression.split("\\"+o);
            System.out.println("expressionArray.length="+expressionArray.length);
            if(expressionArray.length==2){
                return expressionArray;
            }
        }
        return null;
    }
}
